package com.ruoyi.common.typehandler;

import com.ruoyi.common.json.JsonList;
import com.ruoyi.common.json.JsonUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.logging.log4j.util.Strings;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JsonListTypeHandler extends BaseTypeHandler<JsonList> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, JsonList parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter.toString());
    }


    /**
     * Gets the nullable result.
     *
     * @param rs         the rs
     * @param columnName Colunm name, when configuration <code>useColumnLabel</code> is <code>false</code>
     * @return the nullable result
     * @throws SQLException the SQL exception
     */
    @Override
    public JsonList getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        if (Strings.isNotBlank(value)) {
            return JsonUtil.toJsonList(value);
        }
        return new JsonList();
    }

    @Override
    public JsonList getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return new JsonList();
    }

    @Override
    public JsonList getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return new JsonList();
    }
}
